package com.xuchen.zhenyang.controller;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.PinyinUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.xuchen.zhenyang.base.BaseCheckBox;
import com.xuchen.zhenyang.base.BaseQuery;
import com.xuchen.zhenyang.base.Result;
import com.xuchen.zhenyang.controller.base.BaseController;
import com.xuchen.zhenyang.core.annotation.CheckNullUpdate;
import com.xuchen.zhenyang.core.annotation.RequestLog;
import com.xuchen.zhenyang.entity.User;
import com.xuchen.zhenyang.entity.base.MyEntityWrapper;
import com.xuchen.zhenyang.enums.UserTypeEnums;
import com.xuchen.zhenyang.exception.BusinessException;
import com.xuchen.zhenyang.service.UserService;
import com.xuchen.zhenyang.util.MyUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("user")
@RequiresPermissions("user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;
    @Value("${userImgDir}")
    String userImgDir;

    @GetMapping("")
    String index(HttpServletRequest request) {
        setAttributeEnums(request);
        return "user/user-list";
    }

    @CheckNullUpdate({"userName"})
    @PostMapping("editText")
    @ResponseBody
    @RequestLog
    Result editText(User myEntity) {
        myEntity.setUpdateUser(getSessionUserName());
        myEntity.setUpdateTime(new Date());
        updateUserName(myEntity);
        try {
            userService.updateById(myEntity);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(String.format("用户[%s]已存在", myEntity.getUserName()));
        }
        return Result.success();
    }

    @GetMapping("list")
    @ResponseBody
    Result list(BaseQuery baseQuery, User myEntity, String params, HttpServletRequest request) {
        if (StrUtil.isNotBlank(params)) {
            myEntity = JSONObject.parseObject(params).toJavaObject(User.class);
        }
        MyEntityWrapper<User> wrapper = new MyEntityWrapper<>(baseQuery, myEntity);
        wrapper.eq("user_type").like("user_name").like("shop_name").eq("status").orderBy("user_name");
        List<User> list = userService.selectList(wrapper);
        return Result.success(PageHelper.freeTotal(), list);
    }

    @PostMapping("checkboxUpdate")
    @ResponseBody
    @RequestLog
    Result checkboxUpdate(BaseCheckBox checkBox) {
        User myEntity = new User();
        myEntity.setUserId(checkBox.getId());
        myEntity.setStatus(checkBox.isChecked() ? 1 : 0);
        userService.updateById(myEntity);
        return Result.success();
    }

    @GetMapping("toAdd")
    String toAdd(HttpServletRequest request) {
        setAttributeEnums(request);
        return "user/user-add";
    }

    @PostMapping("doAdd")
    @ResponseBody
    Result doAdd(User myEntity, String imgFile) {
        logger.info(myEntity.toString());
        myEntity.setCreateUser(getSessionUserName());
        updateUserName(myEntity);
        try {
            userService.insert(myEntity);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(String.format("用户[%s]已存在", myEntity.getUserName()));
        }
        if (StrUtil.isNotBlank(imgFile)) {
            File newFile = MyUtils.createFileFromStr(imgFile, imgPath + userImgDir, myEntity.getUserId() + ".jpg");
            myEntity.setUserImg(imgDomain + userImgDir + myEntity.getUserId() + ".jpg");
            userService.updateById(myEntity);
        }
        return Result.success();
    }

    @GetMapping("toEdit")
    String toEdit(User myEntity, HttpServletRequest request) {
        setAttributeEnums(request);
        request.setAttribute("myEntity", userService.selectById(myEntity));
        return "user/user-edit";
    }

    @PostMapping("doEdit")
    @ResponseBody
    Result doEdit(User myEntity, String imgFile) {
        logger.info("url:[user/doEdit];" + myEntity);
        myEntity.setUpdateUser(getSessionUserName());
        myEntity.setUpdateTime(new Date());
        updateUserName(myEntity);
        if (StrUtil.isNotBlank(imgFile)) {
            File newFile = MyUtils.createFileFromStr(imgFile, imgPath + userImgDir, myEntity.getUserId() + ".jpg");
            logger.info("用户头像更新:" + newFile.getAbsolutePath());
            myEntity.setUserImg(imgDomain + userImgDir + myEntity.getUserId() + ".jpg");
        }
        try {
            userService.updateById(myEntity);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(String.format("用户[%s]已存在", myEntity.getUserName()));
        }
        return Result.success();
    }

    @PostMapping("deleteImg")
    @ResponseBody
    @RequestLog
    Result deleteImg(Integer id) {
        User myEntity = new User();
        myEntity.setUserId(id);
        myEntity = userService.selectById(myEntity);
        myEntity.setUpdateUser(getSessionUserName());
        myEntity.setUpdateTime(new Date());
        myEntity.setUserImg(null);
        userService.updateAllColumnById(myEntity);
        File file = new File(imgPath + userImgDir + myEntity.getUserId() + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        return Result.success();
    }

    private void setAttributeEnums(HttpServletRequest request) {
        request.setAttribute("userType", UserTypeEnums.getMap());
    }

    /**
     * 给对象中的userName开头加上姓氏首字母
     */
    private void updateUserName(User user) {
        if (StrUtil.isBlank(user.getUserName())) {
            return;
        }
        String userName = user.getUserName().trim();
        char name = userName.charAt(0);
        char chr = PinyinUtil.getFirstLetter(name);
        if (!CharUtil.isLetterLower(name) && CharUtil.isLetterLower(chr)) {
            user.setUserName(chr + userName);
        }
    }
}
